package chen.web.config;

import java.net.URI;

public class SiteConfig extends Config{
	
	private static String BaseURLPropertyName = "baseURL";
	private static String SiteNamePropertyName = "siteName";
	private static String DescriptionPropertyName = "description";
	private static String AdminEmailPropertyName = "adminEmail";
	
	private  String baseURL;
	private  String siteName;
	private  String description;
	private  String adminEmail;
	
	private SiteConfig(Builder builder){
		this.baseURL = builder.baseURL;
		this.siteName = builder.siteName;
		this.description = builder.description;
		this.adminEmail = builder.adminEmail;
	}
	
	protected SiteConfig() {}
	
	@Override
	protected void persist(){
		this.setProperty(BaseURLPropertyName, baseURL);
		this.setProperty(SiteNamePropertyName, siteName);
		this.setProperty(DescriptionPropertyName, description);
		this.setProperty(AdminEmailPropertyName, adminEmail);
	}
	
	@Override
	protected void load() {
		// TODO Auto-generated method stub
		this.baseURL = this.getProperty(BaseURLPropertyName);
		this.siteName = this.getProperty(SiteNamePropertyName);
		this.description = this.getProperty(DescriptionPropertyName);
		this.adminEmail = this.getProperty(AdminEmailPropertyName);
	}
	
	public URI getBaseURI(){
		return URI.create(getBaseURL());
	}
	
	public String getBaseURL() {
		return baseURL;
	}


	public String getSiteName() {
		return siteName;
	}


	public String getDescription() {
		return description;
	}


	public String getAdminEmail() {
		return adminEmail;
	}

	
	public static class Builder{
		private String baseURL;
		private String siteName;
		private String description;
		private String adminEmail;
		
		public SiteConfig build(){
			return new SiteConfig(this);
		}
		
		public Builder description(String description){
			this.description = description;
			return this;
		}
		
		public Builder adminEmail(String adminEmail){
			this.adminEmail = adminEmail;
			return this;
		}
		
		public Builder siteName(String siteName){
			this.siteName = siteName;
			return this;
		}
		
		public Builder baseURL(String baseURL){
			baseURL = baseURL.trim();
			if(baseURL.endsWith("/")){
				baseURL = baseURL.substring(0, baseURL.length()-1);
			}
			URI test = URI.create(baseURL);
			if(!test.isAbsolute()){
				baseURL = "http://" + baseURL;
			}
			this.baseURL = baseURL;
			return this;
		}
	}

}
